package com.hanlin.backend.common.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hanlin.backend.common.dto.MailBase;
import com.hanlin.backend.common.dto.SettingDto;
import com.hanlin.backend.common.entity.HlSetting;
import com.hanlin.backend.common.mapper.HlSettingMapper;
import com.hanlin.backend.common.service.HlSettingService;
import com.hanlin.backend.common.util.MailUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 全局参数表 服务实现类
 * </p>
 *
 * @author hl.yuan
 * @since 2021-01-06
 */
@Service
public class HlSettingServiceImpl extends ServiceImpl<HlSettingMapper, HlSetting> implements HlSettingService {


    @Override
    public HlSetting getSetting(String model, String name) {
        QueryWrapper<HlSetting> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("model", model);
        queryWrapper.eq("name", name);
        HlSetting hlSetting = getBaseMapper().selectOne(queryWrapper);
        return hlSetting;
    }

    @Override
    public String getSetting(String model, String name, String defaults) {
        HlSetting setting = getSetting(model, name);
        if (setting == null) {
            return defaults;
        }
        return setting.getValue();
    }

    @Override
    public List<HlSetting> getTable() {
        QueryWrapper<HlSetting> queryWrapper = new QueryWrapper<>();
        List<HlSetting> settingList = getBaseMapper().selectList(queryWrapper);
        return settingList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSetting(HlSetting setting) {
        if (setting != null) {
            saveOrUpdate(setting);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteSetting(int id) {
        this.removeById(id);
    }

    @Override
    public void saveMail(String model, String name, String value) {
        HlSetting setting = this.getSetting(model, name);
        setting.setValue(value);
        saveOrUpdate(setting);
        // 邮件发送
        MailBase mailBase = new MailBase();

        String replace = value.replace("{content}", "邮件签名发生变化，请注意查收。");

        mailBase.setContent(replace);

        mailBase.setSubject("邮件签名发生变化，请注意~");

        String mailDefault = this.getSetting("COMMON", "MAILDEFAULT", "17386677278@163.com");

        mailBase.setReceivers(StrUtil.split(mailDefault, ','));

        MailUtil.mailSendHtml(mailBase);
    }

    @Override
    public IPage<HlSetting> getTable(SettingDto dto) {
        IPage iPage = dto.buildPage();
        IPage<HlSetting> list = getBaseMapper().getTable(iPage, dto);
        return list;
    }
}
